package com.geelaro.register.controller;

import java.util.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.geelaro.register.domain.entity.Users;
import com.geelaro.register.service.UsersService;

@Controller
public class UserControllerPage {

	@Autowired
	private UsersService usersService;

	@RequestMapping("/user/findAll")
	public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
			@RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
		// System.out.println("============================");

		Page<Users> users = usersService.findAll(pageNum, pageSize);
		// System.out.println("总页数" + users.getTotalPages());
		// System.out.println("当前页是：" + pageNum);
		// System.out.println("分页数据：");
		Iterator<Users> u = users.iterator();

		/*
		 * while (u.hasNext()) { System.out.println(u.next().toString()); }
		 */
		model.addAttribute("users", users);
		return "emp/userpage";
	}

	//跳转到新增编辑页面
	@RequestMapping("/user/toAdd")
	public String toAdd() {
		return "emp/userpageadd";
	}
	//添加成功
	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	public String add(Users user) {
		usersService.save(user);
		return "redirect:/user/findAll";
	}

	// 跳转到编辑界面
	@GetMapping("/user/toEdit/{id}")
	public String toEdit(@PathVariable("id") long id, Model model) {
		Users user = usersService.findUserById(id);
		model.addAttribute("user", user);
		return "emp/userpageupdate";
	}

	// 编辑成功
	@RequestMapping(value = "/user/edit", method = RequestMethod.POST)
	public String edit(Users user) {
		usersService.save(user);
		return "redirect:/user/findAll";
	}

	// 删除

	@GetMapping("/user/delete/{id}")
	public String delete(@PathVariable("id") Long id) {
		usersService.deleteById(id);
		return "redirect:/user/findAll";
	}

	/*
	 * @GetMapping("/deleteUserById/{id}") public String
	 * deleteUserById(@PathVariable("id") Integer id) {
	 * usersService.deleteUserById(id); return "redirect:/users"; }
	 */
}
